/**
 * Created by huanggw on 2015/11/6.
 */
var  client = require('../database');
var  uid = require('../utils/uuid');//用于生成id
function  User(user) {
    this.name = user.name;
    this.email = user.email;
    this.password = user.password;
}
var tableName = "user";
mysql = client.getDbCon();
module.exports = User;
//新增用户
User.save = function (params ,callback) {
    // 用户对象
    uuid = uid.v4();
    //检查用户名是否存在
    var sql = "select * from users where username='"+params.username+"'";
    mysql.query(sql, function(err, result) {
        if(err){
            console.log('[SELECT ERROR] - ',err.message);
            return;
        }
        if(result[0]) {
            callback({regStatus: 0, content:"用户名已被注册"});
            return;
        }
        var sql = "select * from users where useremail='"+params.useremail+"'";
        mysql.query(sql, function(err, result) {
            if(err){
                console.log('[SELECT ERROR] - ',err.message);
                return;
            }
            if(!result[0]) {
                //插入数据库
                var sql ="insert into users (id,username, useremail,password) values(?,?,?,?)";

                mysql.query(sql,[uuid,params.username, params.useremail,params.password],function(err,result,fields){
                    if (err) {
                        console.log('[REGIST ERROR] - ',err.message);
                        return;
                    } else {
                        console.log('---------------REGIST----------------');
                        //返回用户id
                        callback({regStatus: 1, content: params.username});
                    }
                });
            }
            else {
                callback({regStatus: 0, content: "邮箱已被注册"})
            }
        })
    })
};

//获取用户
User.get =  function get(params, callback) {
    // 读取 users 集合
    var sql = "select password from users where username='"+params.username+"' or useremail='"+params.username+"'";
    mysql.query(sql,function(err,result,fields){
        if(err){
            console.log('[SELECT ERROR] - ',err.message);
            return;
        }
        if(!result[0]) {
            callback({loginStatus: 0, content: "用户不存在"});
            return;
        }
        if(params.password != result[0].password) {
            callback({loginStatus: 0, content: "密码不正确"});
            return;
        }
        else {
            callback({loginStatus: 1, content: params.username});
        }
    })

};